import 'base_generator.dart';

/// 页面生成器
class PageGenerator extends BaseGenerator {
  static void generate(String name, Map<String, dynamic> options) {
    if (!BaseGenerator.isValidName(name)) {
      BaseGenerator.printError('页面名称格式不正确: $name');
      return;
    }

    final String moduleName = options['module'] ?? '';
    final bool isSimple = options['simple'] == true;
    final bool withController = options['with-controller'] == true;

    final String className = BaseGenerator.toPascalCase(name);
    final String fileName = BaseGenerator.toSnakeCase(name);
    final String modulePath = BaseGenerator.getModulePath(moduleName);
    
    // 创建页面目录
    final String pageDir = '$modulePath/presentation/pages';
    BaseGenerator.createDirectoryIfNotExists(pageDir);
    
    // 生成页面文件
    final String pagePath = '$pageDir/${fileName}_page.dart';
    final String pageContent = _generatePageContent(className, moduleName, isSimple, withController);
    
    BaseGenerator.writeFile(pagePath, pageContent);
    
    // 如果需要同时创建控制器
    if (withController && !isSimple) {
      _createController(className, moduleName);
    }
    
    // 添加路由导入
    BaseGenerator.addRouteImport('../features/${BaseGenerator.toSnakeCase(moduleName)}/presentation/pages/${fileName}_page.dart');
    
    BaseGenerator.printSuccess('页面', className, pagePath);
    
    if (withController && !isSimple) {
      print('📝 同时创建了对应的控制器');
    }
    
    _printUsageInstructions(className, fileName, moduleName, isSimple);
  }

  static String _generatePageContent(String className, String moduleName, bool isSimple, bool withController) {
    final String controllerName = '${className}Controller';
    final String controllerImport = withController && !isSimple ? 
        "import '../controllers/${BaseGenerator.toSnakeCase(className)}_controller.dart';" : '';

    if (isSimple) {
      return BaseGenerator.generateFileHeader(
        '${className}Page',
        '${className}页面 - 简单StatefulWidget实现'
      ) + '''
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ${className}Page extends StatefulWidget {
  const ${className}Page({Key? key}) : super(key: key);

  @override
  State<${className}Page> createState() => _${className}PageState();
}

class _${className}PageState extends State<${className}Page> {
  @override
  void initState() {
    super.initState();
    _initData();
  }

  void _initData() {
    // 初始化数据
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('$className'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '$className页面',
                style: TextStyle(
                  fontSize: 24.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 16.h),
              Text(
                '这是$className页面的内容',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[600],
                ),
              ),
              SizedBox(height: 24.h),
              ElevatedButton(
                onPressed: _handleButtonPress,
                child: const Text('执行操作'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _handleButtonPress() {
    // 处理按钮点击
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('按钮被点击了'),
      ),
    );
  }

  @override
  void dispose() {
    // 清理资源
    super.dispose();
  }
}
''';
    }

    // GetX版本
    return BaseGenerator.generateFileHeader(
      '${className}Page',
      '${className}页面 - 基于GetX的响应式页面'
    ) + '''
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
$controllerImport

class ${className}Page extends StatelessWidget {
  const ${className}Page({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
${withController ? '''    final controller = Get.put(${controllerName}());
    
    return GetBuilder<${controllerName}>(
      builder: (controller) {''' : '''    return Scaffold('''}
        ${withController ? 'return Scaffold(' : ''}
          appBar: AppBar(
            title: const Text('$className'),
            centerTitle: true,
          ),
          body: SafeArea(
            child: Padding(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '$className页面',
                    style: TextStyle(
                      fontSize: 24.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 16.h),
                  Text(
                    '这是$className页面的内容',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                  SizedBox(height: 24.h),
${withController ? '''                  Obx(() => Text(
                    '计数器: \${controller.count}',
                    style: TextStyle(fontSize: 18.sp),
                  )),
                  SizedBox(height: 16.h),
                  Row(
                    children: [
                      ElevatedButton(
                        onPressed: controller.increment,
                        child: const Text('增加'),
                      ),
                      SizedBox(width: 16.w),
                      ElevatedButton(
                        onPressed: controller.decrement,
                        child: const Text('减少'),
                      ),
                    ],
                  ),''' : '''                  ElevatedButton(
                    onPressed: () {
                      Get.snackbar('提示', '按钮被点击了');
                    },
                    child: const Text('执行操作'),
                  ),'''}
                ],
              ),
            ),
          ),
        ${withController ? ');' : ''}
${withController ? '''      },
    );''' : ''}
  }
}
''';
  }

  static void _createController(String className, String moduleName) {
    final String controllerName = '${className}Controller';
    final String fileName = BaseGenerator.toSnakeCase(className);
    final String modulePath = BaseGenerator.getModulePath(moduleName);
    
    // 创建控制器目录
    final String controllerDir = '$modulePath/presentation/controllers';
    BaseGenerator.createDirectoryIfNotExists(controllerDir);
    
    // 生成控制器文件
    final String controllerPath = '$controllerDir/${fileName}_controller.dart';
    final String controllerContent = _generateControllerContent(controllerName, className);
    
    BaseGenerator.writeFile(controllerPath, controllerContent);
  }

  static String _generateControllerContent(String controllerName, String className) {
    return BaseGenerator.generateFileHeader(
      controllerName,
      '${className}页面控制器'
    ) + '''
import 'package:get/get.dart';

class $controllerName extends GetxController {
  // 响应式变量
  final _count = 0.obs;
  final _isLoading = false.obs;
  
  // Getter
  int get count => _count.value;
  bool get isLoading => _isLoading.value;

  @override
  void onInit() {
    super.onInit();
    _initController();
  }

  void _initController() {
    // 初始化控制器
  }

  /// 增加计数
  void increment() {
    _count.value++;
  }

  /// 减少计数
  void decrement() {
    if (_count.value > 0) {
      _count.value--;
    }
  }

  /// 重置计数
  void reset() {
    _count.value = 0;
  }

  /// 设置加载状态
  void setLoading(bool loading) {
    _isLoading.value = loading;
  }

  /// 执行异步操作示例
  Future<void> performAsyncOperation() async {
    try {
      setLoading(true);
      
      // 模拟异步操作
      await Future.delayed(const Duration(seconds: 2));
      
      // 处理结果
      Get.snackbar('成功', '操作完成');
      
    } catch (e) {
      Get.snackbar('错误', '操作失败: \$e');
    } finally {
      setLoading(false);
    }
  }

  @override
  void onClose() {
    // 清理资源
    super.onClose();
  }
}
''';
  }

  static void _printUsageInstructions(String className, String fileName, String moduleName, bool isSimple) {
    print('\n📋 使用说明:');
    print('1. 在routes.dart中添加路由:');
    print('   GetPage(');
    print('     name: \'/${BaseGenerator.toKebabCase(className)}\',');
    print('     page: () => const ${className}Page(),');
    print('   ),');
    print('');
    print('2. 导航到页面:');
    print('   Get.toNamed(\'/${BaseGenerator.toKebabCase(className)}\');');
    
    if (!isSimple) {
      print('');
      print('3. 在其他地方获取控制器:');
      print('   final controller = Get.find<${className}Controller>();');
    }
  }
}
''';
  }
}